﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace Adjunct.Framework.NuGet
{
	public class RepositoriesConfig
	{
		private readonly List<string> _paths = new List<string>();

		public void Add(string relativePathtoPackagesConfig)
		{
			if (!_paths.Contains(relativePathtoPackagesConfig))
			{
				_paths.Add(relativePathtoPackagesConfig);
			}
		}

		public void Save(string path)
		{
			IEnumerable<XElement> elements = from p in _paths
			                                 orderby p
			                                 select new XElement("repository", new XAttribute("path", p));
			XDocument document = new XDocument(new XElement("repositories", elements));
			document.Save(path);
		}

		public static RepositoriesConfig Load(string path)
		{
			RepositoriesConfig repositoriesConfig = new RepositoriesConfig();
			if (File.Exists(path))
			{
				XDocument document = XDocument.Load(path);
				foreach (XElement element in document.Root.Elements("repository"))
				{
					repositoriesConfig.Add(element.AttributeValue("path"));
				}
			}
			return repositoriesConfig;
		}
	}
}

//<?xml version="1.0" encoding="utf-8"?>
//<repositories>
//  <repository path="path.to\packages.config" />
//</repositories>